#!/usr/bin/env node

const readline = require('readline')
const execSync = require('child_process').execSync
const fs = require('fs')
const path = require('path')
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
})
// 终端获取commit ID
let commitID = ''
let currentCommit = '' // 当前commitId
let currentBranch = '' // 当前分支
let compairBranch = '' // 比较目标的分支
rl.question('请输入比较的commitId：', (text) => {
	commitID = text
	currentBranch = execSync('git branch --show-current', { encoding: 'utf8' })
	currentCommit = execSync('git rev-parse HEAD', { encoding: 'utf8' })
	gitCopy(text)
	rl.close()
})
let currentDir = [] // 需要比对文件的当前目录下的所有文件
let toCompariDir = [] // 需要比对文件目标的目录
const toCompariFile = {} // 存取需要比对文件内容
// 复制文件
function gitCopy(string) {
	try {
		// 将本地的文件目录存到数组
		currentDir = saveDir()
		// 复制 commitID src/locales文件到当前分支
		execSync('git stash save change banrch')
		execSync(`git checkout ${string}`)
		commitID = execSync('git rev-parse HEAD', { encoding: 'utf8' })
		compairBranch = execSync('git branch --show-current', { encoding: 'utf8' })
		// 切换到目标分支/hash=>将比较目标的文件目录存起来
		toCompariDir = saveDir()
		toCompariDir.forEach((i, index) => {
			if (i.indexOf('.json') !== -1) {
				const key = path.parse(`./src/locales/zh_CN/${i}`).name
				const jsonData = fs.readFileSync(`./src/locales/zh_CN/${i}`)
				toCompariFile[key] = JSON.parse(jsonData.toString())
			}
		})
		// 回到本分支
		execSync(`git checkout ${currentBranch}`)
		const stashList = execSync(`git stash list`, {
			encoding: 'utf8'
		})
		if (stashList) {
			execSync(`git stash pop`)
		}
		compariDir(currentDir, toCompariDir)
	} catch (err) {
		// 回到本分支
		execSync(`git checkout ${currentBranch}`)
		const stashList = execSync(`git stash list`, {
			encoding: 'utf8'
		})
		if (stashList) {
			execSync(`git stash pop`)
		}
	}
}
// 将文件目录存到数组
function saveDir() {
	const arr = []
	const dir = fs.readdirSync('./src/locales/zh_CN')
	if (dir.length) {
		dir.forEach((i) => {
			if (
				fs.statSync(`./src/locales/zh_CN/${i}`).isFile() &&
				i.indexOf('.json') !== -1 &&
				i.indexOf('dict') === -1
			) {
				arr.push(i)
			}
		})
	}
	return arr
}
// 比对目录文件
async function compariDir(cur, toCompariDir) {
	const now = Ymd()
	const filePath = `./${now}.json`
	const result = {}
	for (let i = 0; i < cur.length; i++) {
		if (toCompariDir.indexOf(cur[i]) !== -1) {
			const key = cur[i].substr(0, cur[i].length - 5)
			const curJson = JSON.parse(
				fs.readFileSync(`./src/locales/zh_CN/${cur[i]}`).toString()
			)
			result[key] = diffJson(curJson, toCompariFile[key])
			// fs.appendFileSync(
			// 	filePath,
			// 	JSON.stringify(result[key], null, '\t'),
			// 	'utf8'
			// )
		}
	}
	fs.writeFileSync(filePath, JSON.stringify(result, null, '\t'), 'utf8')
	const str = `比较时间：${now}
1.比较commitId：
当前:${currentCommit}
目标:${commitID}
2.比较分支：
当前:${currentBranch}
目标:${compairBranch}`
	fs.writeFileSync('./compair-record.txt', str)
}
// 当前时间
function Ymd() {
	const date = new Date()
	const y = date.getFullYear()
	const m = date.getMonth() + 1
	const d = date.getDate()
	const h = date.getHours()
	const minutes = date.getMinutes()
	return `${y}_${m}_${d}_${h}_${minutes}`
}
// JSON对象比较
function diffJson(currentVal, compariVal) {
	// console.log(currentVal, compariVal)
	const result = {}
	for (const key in currentVal) {
		// 判断数据为对象/数组时进行递归
		if (getTypeByObj(currentVal[key]) === 'Array') {
			// if (getTypeByObj(currentVal[key]) === 'Array') {
			// 	return result
			// }
		}
		if (getTypeByObj(currentVal[key]) === 'Object' && compariVal[key]) {
			const data = diffJson(currentVal[key], compariVal[key])
			if (Object.keys(data).length) {
				result[key] = data
			}
			return result
		}
		if (currentVal[key] !== compariVal[key]) {
			result[key] = currentVal[key]
		}
	}
	return result
}

/**
 * 获取数据类型
 * @param {*} obj
 */
function getTypeByObj(obj) {
	return Object.prototype.toString
		.call(obj)
		.match(/^\[object ([a-zA-Z]*)\]$/)[1]
}

// 将目标文件目录存到数组

// d5e7ee418552c9b15f0eb74e2073108909abe551
